package com.mls.fivedistrict.controller.portal;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.common.RequestHolder;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.controller.BaseController;
import com.mls.fivedistrict.pojo.UserMessage;
import com.mls.fivedistrict.server.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * Created by chenxiuxiang on 2018/6/21.
 */
@RestController("portalUserMessageController")
@RequestMapping("/api/app")
public class UserMessageController extends BaseController {
    @Autowired
    UserMessageService userMessageService;

    @GetMapping("/v1/userMessages")
    public ServiceResponse getUserMessages() {
        PageFilter pageFilter = RequestHolder.getPageFilter();
        Wrapper wrapper = pageFilter.getWrapper();
        if (wrapper == null) {
            wrapper = Condition.create();
        }
        wrapper.eq("target_user_id", getUser().getId());
        PageHelper.startPage(pageFilter.getPageNum(), pageFilter.getPageSize());
        List list = userMessageService.selectList(wrapper);
        PageInfo<Object> objectPageInfo = new PageInfo<>(list, 5);
        return ServiceResponse.createSuccessResponse(objectPageInfo);
    }


    @PostMapping("/v1/userMessage/{userMessageId}")
    public ServiceResponse readUserMessage(@PathVariable Long userMessageId) {
        UserMessage userMessage = userMessageService.selectById(userMessageId);
        if (userMessage == null) {
            return ServiceResponse.createErrorResponse("消息不存在");
        }
        userMessage.setRead(true);
        userMessage.setViewDate(new Date());
        boolean b = userMessageService.updateById(userMessage);
        if (b) {
            return ServiceResponse.createSuccessResponse();
        } else {
            return ServiceResponse.createErrorResponse("请求出错");
        }
    }


    @DeleteMapping("/v1/userMessage/{userMessageId}")
    public ServiceResponse deleteUserMessage(@PathVariable Long userMessageId) {
        boolean b = userMessageService.deleteById(userMessageId);
        if (b) {
            return ServiceResponse.createSuccessResponse();
        } else {
            return ServiceResponse.createErrorResponse("操作失败");
        }
    }

    @GetMapping("/v1/userMessage/{userMessageId}")
    public ServiceResponse getUserMessageDetail(@PathVariable Long userMessageId) {
        UserMessage userMessage = userMessageService.selectById(userMessageId);

        if (userMessage != null) {
            return ServiceResponse.createSuccessResponse(userMessage);
        } else {
            return ServiceResponse.createErrorResponse("获取失败");
        }
    }
}
